<?php if(!defined('FRAME')) exit('No direct script access allowed');
/**
 * URI
 * @author wisoch@hotmail.com
 *
 */
class Uri {

	private $url;

	private $scheme;

	private $host;

	private $port;

	private $user;

	private $pass;

	private $path;

	private $query;

	private $fragment;

	private $ext = 'html';

	private $params = array();
	
	private static $instance;

	public static function Instance() {
        if( ! (self::$instance instanceof self) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

	public function __construct() {
		$this->url = $this->currUri();
		if($this->url) {
			$this->parse($this->url);
		}
		$ext = pathinfo($this->path, PATHINFO_EXTENSION);
		$ext? $this->ext = $ext: '';
	}

	public function params() {
		return $this->params;
	}

	public function parse($url) {
		$retval = false;
		if(($urlArr = parse_url($url)) != false) {
			$retval = TRUE;
			isset($urlArr['scheme'])? $this->scheme = $urlArr['scheme']: '';
			isset($urlArr['host'])? $this->host = $urlArr['host']: '';
			isset($urlArr['port'])? $this->port = $urlArr['port']: '';
			isset($urlArr['user'])? $this->user = $urlArr['user']: '';
			isset($urlArr['pass'])? $this->pass = $urlArr['pass']: '';
			isset($urlArr['path'])? $this->path = $urlArr['path']: '';
			isset($urlArr['query'])? $this->query = $urlArr['query']: '';
			isset($urlArr['fragment'])? $this->fragment = $urlArr['fragment']: '';
			parse_str($this->query, $params);
		}
		return $retval;
	}

	public function setParams($params) {
		$this->params = array_merge($this->params, $params);
	}

	public function getExt() {
		return $this->ext;
	}

	public function query() {
		parse_str($this->query, $query);
		return $query;
	}

	public function resouce($ext = false) {
		if($ext) return $this->path;
		$return = preg_replace('/\.'.$this->ext.'$/ui', '', $this->path);
		return $return;
	}

	public function currUri() {
		$http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']!='off')? 'https://' : 'http://';
		$host = $_SERVER['SERVER_NAME'];
		$port = $_SERVER["SERVER_PORT"]==80? '' : ':' .$_SERVER["SERVER_PORT"];
		$url = $http.$host.$port.$_SERVER["REQUEST_URI"];
		return $url;  
	}
}